#include <bits/stdc++.h>
// 2025/01/23
// tag: 
// Author: Zhang Muen
using namespace std;
int n, m;
char maze[301][301];
int bx, by;
bool vis[301][301];
int endpoint[26][4];

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++){
            cin >> maze[i][j];
            if (maze[i][j] == '@')
                bx = i, by = j;
            if (maze[i][j] >= 'A' && maze[i][j] <= 'Z'){
                if (endpoint[maze[i][j] - 'A'][0] == 0)
                    endpoint[maze[i][j] - 'A'][0] = i, endpoint[maze[i][j] - 'A'][1] = j;
                else
                    endpoint[maze[i][j] - 'A'][2] = i, endpoint[maze[i][j] - 'A'][3] = j;
            }
        }
    queue<pair<int, int>> q;
    int cnt = 0;
    q.push({bx, by});
    while (!q.empty()){
        int size = q.size();
        for (int i = 0; i < size; i++){
            auto cur = q.front();
            q.pop();
            if (cur.first < 1 || cur.first > n || cur.second < 1 || cur.second > m)
                continue;
            if (vis[cur.first][cur.second])
                continue;
            char c = maze[cur.first][cur.second];
            if (c >= 'A' && c <= 'Z')
            {
                if (cur.first == endpoint[c - 'A'][2] && cur.second == endpoint[c - 'A'][3])
                    cur.first = endpoint[c - 'A'][0], cur.second = endpoint[c - 'A'][1];
                else
                    cur.first = endpoint[c - 'A'][2], cur.second = endpoint[c - 'A'][3];
            }
            if (maze[cur.first][cur.second] == '='){
                cout << cnt;
                return 0;
            }
            if (maze[cur.first][cur.second] == '#')
                continue;
            if (vis[cur.first][cur.second])
                continue;  
            if (maze[cur.first][cur.second] == '.')
                vis[cur.first][cur.second] = true;
            q.push({cur.first + 1, cur.second});
            q.push({cur.first - 1, cur.second});
            q.push({cur.first, cur.second + 1});
            q.push({cur.first, cur.second - 1});
            
        }
        cnt++;
    }
    cout << -1;
    return 0;
}